package com.motu.vertx.module.utility.ClassReload;

import com.motu.vertx.module.utility.toolset.Tool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.lang.instrument.UnmodifiableClassException;

public class ClassReloadManager {

	public static final Logger logger = LoggerFactory.getLogger(ClassReloadManager.class);

	private static ClassReloadManager instance = new ClassReloadManager();
	public static ClassReloadManager getInstance() {
		return instance;
	}

	private ClassReloadManager() {

	}

	public static void reload(){
		Scanner.getInstance().reload();
	}

	private static final String DEFAULT_RELOD_FILE_PATH = "";

	/**
	 * 
	 * @param classPath pakage.test
	 * @param filePath  /E:/workSpaceTest/test.jar
	 */
	public void reloadClass(String classPath, String filePath) {
		if (classPath == null || classPath.trim().equals("")) {
			logger.error("出错：" + Thread.getAllStackTraces());
			return;
		}

		filePath = filePath == null ? DEFAULT_RELOD_FILE_PATH : filePath;
		try {
			logger.info("classPath:"+classPath);
			logger.info("filePath:"+filePath);
			Class<?> reloadClass = Class.forName(classPath);

			logger.info("reloadClass.getName()"+reloadClass.getName());
			ClassReloader.reload(reloadClass, new File(filePath));

		} catch (ClassNotFoundException e) {
			logger.error("ClassNotFoundException....");
			logger.error(Tool.getException(e));
		} catch (IOException e) {
			logger.error("IOException....");
			logger.error(Tool.getException(e));
		} catch (UnmodifiableClassException e) {
			logger.error("UnmodifiableClassException....");
			logger.error(Tool.getException(e));
		} catch (NullPointerException e) {
			logger.error("NullPointerException....");
			logger.error(Tool.getException(e));
		} catch (UnsupportedOperationException e) {
			logger.error("UnsupportedOperationException....");
			logger.error(Tool.getException(e));
		} catch (Exception e) {
			logger.error("Exception....");
			logger.error(Tool.getException(e));
		}

	}
}
